package src.other.beogold.u9c.request;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.*;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.ServiceRequest__c;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.XoqlService;
import src.other.beogold.u9c.client.PaasClient;
import src.other.beogold.u9c.utils.DateTools;
import src.other.beogold.u9c.utils.HCXObjectService;
import src.other.beogold.u9c.utils.Result;

import java.util.List;
import java.util.Map;

/**
 * @Description: 推送服务请求
 * @Author: lys
 * @Date: 2025-09-09 18:12
 */
@RestApi(baseUrl = "/service")
public class PushRequest implements ApprovalEvent {

    private static final Logger logger = LoggerFactory.getLogger();

    /**
     * 审批触发事件
     * @param request
     * @return
     */
    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) {
        Long requestId = request.getDataId();
        logger.info("审批事件推送服务请求 requestId = " + requestId);
        startPush(requestId);

        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        return response;
    }

    public static void main(String[] args) {
        PushRequest pushRequest = new PushRequest();
        //pushRequest.startPush(3976428715738156L);

        //String str = "{\"errormessage\":\"\",\"issuccess\":0,\"ticketnumber\":\"CASE202509120006\"}";
        //pushRequest.syncServiceRequestStatus(JSONObject.parseObject(str));
    }

    /**
     * 同步服务请求同步状态 (服务端发送同步状态 ，CRM接收)
     * @param prop
     * @return
     */
    @RestMapping(value = "/syncServiceRequestStatus", method = RequestMethod.POST)
    public Result syncServiceRequestStatus(@RestBeanParam(name = "body") JSONObject prop) {
        logger.info("同步服务请求同步状态: " + prop);
        if (prop == null) {
            return Result.error("入参不可为空");
        }

        String ticketnumber = prop.getString("ticketnumber");
        Integer issuccess = prop.getInteger("issuccess"); // 0:成功 1:失败
        if (ticketnumber == null || issuccess == null) {
            logger.error("'案例号'、'是否成功'不可为空");
            return Result.error("'案例号'、'是否成功'不可为空");
        }

        String sql = String.format("select id from serviceRequest__c where ticketnumber__c = '%s'", ticketnumber);
        ServiceRequest__c upSq = HCXObjectService.queryOne(sql);
        if(upSq == null){
            logger.error("查询不到对应的服务请求数据");
            return Result.error("查询不到对应的服务请求数据");
        }
        upSq.setIssuccess__c(issuccess == 0 ? 2 : 3);
        upSq.setErrormessage__c(prop.getString("errormessage"));
        logger.info("upSq : " + upSq);
        HCXObjectService.update(upSq);

        logger.info("同步状态成功");
        return Result.success("同步状态成功");
    }

    /**
     * 推送服务请求
     * @param requestId
     * @return
     */
    @RestMapping(value = "/pushServiceRequest", method = RequestMethod.POST)
    public Result startPush(@RestQueryParam(name = "id") Long requestId) {
        logger.info("推送服务请求 requestId = " + requestId);
        try {
            // 查询主表
            ServiceRequest__c master = new ServiceRequest__c();
            master.setId(requestId);
            master = HCXObjectService.get(master);
            if (master == null) {
                logger.error("查询服务请求数据异常");
                return Result.error("查询服务请求数据异常");
            }

            // 查询明细
            String sql = "select id,logisticsCode__c,productId__c.productName productName,number__c,buydate__c,endDate__c,purchaseSource__c " +
                    " from serviceRequestEntry__c where serviceRequest__c = " + requestId;
            List<JSONObject> detailList = XoqlService.instance().query(sql, true, true).getRecords();

            // 省市区
            Map<String, String> provinceMap = HCXObjectService.getPickMap("province", "optionApiKey");
            Map<String, String> cityMap = HCXObjectService.getPickMap("city", "optionApiKey");
            Map<String, String> regionMap = HCXObjectService.getPickMap("district", "optionApiKey");

            // 获取主表、明细对象中的选项
            JSONObject masterOpt = HCXObjectService.getEntityOpt("serviceRequest__c", "businessline__c-value-apiKey",
                    "requestType__c-value-apiKey", "prioritycode__c-value-apiKey", "emergencyDegree__c-value-apiKey", "purchaseSource__c-value-apiKey");

            // 封装数据
            JSONObject sendData = new JSONObject();
            sendData.put("new_newcustomers", master.getContact__c()); // 客户
            sendData.put("new_contact", master.getContact__c()); // 联系人
            sendData.put("new_feedbacktel", master.getFeedbacktel__c()); // 联系电话
            sendData.put("angel_sparephone", master.getSparephone__c()); // 备用电话
            sendData.put("angel_callphone", master.getCallphone__c()); // 固定电话
            sendData.put("new_province_id", PaasClient.packOjb("new_province", "new_code", provinceMap.get(master.getFState__c().toString()))); // 省
            sendData.put("new_city_id", PaasClient.packOjb("new_city", "new_code", cityMap.get(master.getFCity__c().toString()))); // 市
            sendData.put("new_county_id", PaasClient.packOjb("new_county", "new_code", regionMap.get(master.getFDistrict__c().toString()))); // 区
            sendData.put("new_address",  master.getAddress__c()); // 地址
            // 商业行业线
            Integer businessLine = masterOpt.getInteger("" + master.getBusinessline__c());
            sendData.put("angel_businessline", PaasClient.packOjb(businessLine));
            // 案例类型
            Integer requestType = masterOpt.getInteger("1_" + master.getRequestType__c());
            sendData.put("new_type", PaasClient.packOjb(requestType));
            // 优先级
            Integer prioritycode = masterOpt.getInteger("2_" + master.getPrioritycode__c());
            sendData.put("prioritycode", PaasClient.packOjb(prioritycode));
            // 紧急程度
            Integer emergencyDegree = masterOpt.getInteger("3_" + master.getEmergencyDegree__c());
            sendData.put("angel_emergencydegree", PaasClient.packOjb(emergencyDegree));
            sendData.put("new_appointmenttime", DateTools.longToString(master.getAppointmenttime__c(), DateTools.FORMATTIME)); // 上门时间起
            sendData.put("new_appointmentendtime", DateTools.longToString(master.getAppointmentendtime__c(), DateTools.FORMATTIME)); // 上门时间止
            // 购机来源
            Integer purchaseSource = masterOpt.getInteger("4_" + master.getPurchaseSource__c());
            sendData.put("angel_purchasesource", PaasClient.packOjb(purchaseSource));
            sendData.put("new_memo", master.getMemo__c()); // 备注
            sendData.put("caseorigincode", PaasClient.packOjb("220")); // 来源（固定值）
            sendData.put("angel_brand_id", PaasClient.packOjb("new_srv_brand", "new_name", "环保")); // 品牌（固定值）

            JSONArray incidentLineList = new JSONArray();
            for (JSONObject detail : detailList) {
                JSONObject obj = new JSONObject();
                obj.put("new_userprofile_number", detail.getString("logisticsCode__c")); // 物流码
                obj.put("new_product_id", PaasClient.packOjb("product", "productnumber", detail.getString("productName"))); // 产品
                obj.put("new_buydate", DateTools.longToString(detail.getLong("buydate__c"), DateTools.FORMATTIME)); // 购买日期
                obj.put("new_enddate", DateTools.longToString(detail.getLong("endDate__c"), DateTools.FORMATTIME)); // 保修截止日期
                obj.put("new_number", detail.getIntValue("number__c")); // 数量
                // 购机来源
                Integer source = masterOpt.getInteger("4_" + detail.getString("purchaseSource__c"));
                obj.put("angel_purchasesource", PaasClient.packOjb(source));
                incidentLineList.add(obj);
            }
            sendData.put("incidentLineList", incidentLineList);
            logger.info("sendData = " + sendData);

            // 推送
            JSONObject reqData = new JSONObject();
            reqData.put("logicalname", "incident");
            reqData.put("data", sendData);
            reqData.put("angel_returnurl", "/api/ASS_NC/updateSyncStatus"); // 回调地址
            JSONObject resData = PaasClient.post(PaasClient.PUSH_SERVICE_REQUEST, reqData);
            logger.info("resData = " + resData);
            if (resData == null) {
                logger.error("推送数据请求异常");
                return Result.error("推送数据请求异常");
            }

            // 更新数据服务编码
            ServiceRequest__c upSq = new ServiceRequest__c();
            upSq.setId(requestId);
            upSq.setTicketnumber__c(resData.getString("ticketnumber"));
            HCXObjectService.update(upSq);

            logger.info("推送成功");
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("推送服务请求异常: " + e.getMessage());
            return Result.error("推送服务请求异常: " + e.getMessage());
        }
    }


}
